<template>
    <el-form label-suffix=":" v-loading="loading" :model="formData" :rules="editable ? formRules : {}" ref="formRef"
        label-width="120px">
        <vp-card>
            <template #header>
                <vp-label zh="基础信息" en="Basic Information" />
            </template>
            <el-row>
                <vp-col :span="3">
                    <el-form-item prop="gysbm">
                        <template #label><vp-label zh="编号" en="Number" /></template>
                        <el-input v-if="editable" v-model="formData.gysbm" maxlength="100" />
                        <span v-else>{{ formData.gysbm }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="3">
                    <el-form-item prop="gysmc">
                        <template #label><vp-label zh="名称(中)" en="Name CN." /></template>
                        <el-input v-if="editable" v-model="formData.gysmc" maxlength="100" />
                        <span v-else>{{ formData.gysmc }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="3">
                    <el-form-item prop="gysywmc">
                        <template #label><vp-label zh="名称(英)" en="Name EN." /></template>
                        <el-input v-if="editable" v-model="formData.gysywmc" maxlength="100" />
                        <span v-else>{{ formData.gysywmc }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="2">
                    <el-form-item prop="jb">
                        <template #label><vp-label zh="级别" en="LV." /></template>
                        <VpDictSelect :lxid="501" :selectedId="formData.jb"
                            @dictSelected="obj => { formData.jb = obj; }" style="width:100%" v-if="editable">
                        </VpDictSelect>
                        <span v-else>{{ formData.jb }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="2">
                    <el-form-item prop="bqydm">
                        <template #label><vp-label zh="本企业代码" en="Enterprise Code" /></template>
                        <el-input v-if="editable" v-model="formData.bqydm" maxlength="100" />
                        <span v-else>{{ formData.bqydm }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="2">
                    <el-form-item prop="dz">
                        <template #label><vp-label zh="地址" en="Address" /></template>
                        <el-input v-if="editable" v-model="formData.dz" maxlength="100" />
                        <span v-else>{{ formData.dz }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="2">
                    <el-form-item prop="bz">
                        <template #label><vp-label zh="备注" en="Remark" /></template>
                        <el-input v-if="editable" v-model="formData.bz" maxlength="100" />
                        <span v-else>{{ formData.bz }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
        </vp-card>

        <vp-card>
            <template #header>
                <vp-label zh="标签" en="label" />
            </template>
            <el-row>
                <vp-col :span="1">
                    <el-form-item label-width="0px">
                        <VpDictCheckbox :lxid="502" :selectedId="formData.tagList" @onConfirm="handleComponentChange"
                            v-if="editable">
                        </VpDictCheckbox>
                        <!-- <el-checkbox-group v-model="formData.tagList" @change="handleComponentChange">
                            <el-checkbox v-for="item in supplierLb" :key="item.key" :label="item.key"
                                class="checkbox-item">
                                {{ item.name }}
                            </el-checkbox>
                        </el-checkbox-group> -->
                    </el-form-item>
                </vp-col>
            </el-row>
            <template v-for="(item, key) in formData.tagVOList" :key="key">
                <el-divider content-position="left">
                    {{ key }}
                </el-divider>
                <el-row>
                    <vp-col :span="3">
                        <el-form-item :prop="`tagVOList.${key}.sqh`">
                            <template #label><vp-label zh="授权号" en="Authorization Number" /></template>
                            <el-input v-if="editable" v-model="item.sqh" maxlength="100" />
                            <span v-else>{{ item.sqh }}</span>
                        </el-form-item>
                    </vp-col>

                    <vp-col :span="3" :prop="`tagVOList.${key}.yxqKs`">
                        <el-form-item>
                            <template #label><vp-label zh="有效期-开始" en="Valid Date Start" /></template>
                            <el-date-picker v-model="item.yxqKs" v-if="editable" type="date"
                                start-placeholder="开始日期/Start Date" value-format="YYYY-MM-DD" class="w100">
                            </el-date-picker>
                            <span v-else>{{ item.yxqKs }}</span>
                        </el-form-item>
                    </vp-col>
                    <vp-col :span="3">
                        <el-form-item :prop="`tagVOList.${key}.yxqJs`">
                            <template #label><vp-label zh="有效期-截止" en="Valid Date End" /></template>
                            <el-date-picker v-model="item.yxqJs" v-if="editable" type="date"
                                start-placeholder="截止日期/Start Date" value-format="YYYY-MM-DD" class="w100">
                            </el-date-picker>
                            <span v-else>{{ item.yxqJs }}</span>
                        </el-form-item>
                    </vp-col>
                </el-row>
                <el-row>
                    <vp-col :span="2">
                        <el-form-item :prop="`tagVOList.${key}.sqfw`">
                            <template #label><vp-label zh="授权范围" en="Scope authorization" /></template>
                            <el-input v-if="editable" type="textarea" v-model="item.sqfw" maxlength="1000" />
                            <span v-else style="white-space:pre">{{ item.sqfw }}</span>
                        </el-form-item>
                    </vp-col>
                    <vp-col :span="2">
                        <el-form-item>
                            <template #label><vp-label zh="附件" en="Attachment" /></template>
                            <RowAttachment :attachmentList="item.attachments" :readOnly="!editable"
                                @attachmentListEmit="getAttachmentListEmit($event, item)"></RowAttachment>
                        </el-form-item>
                    </vp-col>
                </el-row>

                <el-row>
                    <vp-col :span="1">
                        <el-form-item>
                            <template #label><vp-label zh="证书" en="Certificate" /></template>
                            <vp-vxe-table :data="item.tagCertList" row-key="id" minHeight="100">
                                <vxe-column field="lx">
                                    <template #header><vp-label zh="类型" en="Type" /></template>
                                    <template #default="scope">
                                        <el-form-item :prop="`tagVOList.${key}.tagCertList[${scope.rowIndex}].lx`"
                                            label-width="auto">
                                            <el-input v-model="scope.row.lx" placeholder="请输入" v-if="editable" />
                                            <span v-else>{{ scope.row.lx }}</span>
                                        </el-form-item>
                                    </template>
                                </vxe-column>
                                <vxe-column field="bh">
                                    <template #header><vp-label zh="编号" en="Number" /></template>
                                    <template #default="scope">
                                        <el-form-item :prop="`tagVOList.${key}.tagCertList[${scope.rowIndex}].bh`"
                                            label-width="auto">
                                            <el-input v-model="scope.row.bh" placeholder="请输入" v-if="editable" />
                                            <span v-else>{{ scope.row.bh }}</span>
                                        </el-form-item>
                                    </template>
                                </vxe-column>
                                <vxe-column field="sm">
                                    <template #header><vp-label zh="说明" en="Explain" /></template>
                                    <template #default="scope">
                                        <el-form-item :prop="`tagVOList.${key}.tagCertList[${scope.rowIndex}].sm`"
                                            label-width="auto">
                                            <el-input v-model="scope.row.sm" placeholder="请输入" v-if="editable" />
                                            <span v-else>{{ scope.row.sm }}</span>
                                        </el-form-item>
                                    </template>
                                </vxe-column>
                                <vxe-column field="bfrq">
                                    <template #header><vp-label zh="颁发日期" en="Date Issue" /></template>
                                    <template #default="scope">
                                        <el-form-item :prop="`tagVOList.${key}.tagCertList[${scope.rowIndex}].bfrq`"
                                            label-width="auto">
                                            <el-date-picker v-model="scope.row.bfrq" type="date" v-if="editable"
                                                start-placeholder="颁发日期" value-format="YYYY-MM-DD" class="w100">
                                            </el-date-picker>
                                            <span v-else>{{ scope.row.bfrq }}</span>
                                        </el-form-item>
                                    </template>
                                </vxe-column>
                                <vxe-column field="yxq">
                                    <template #header><vp-label zh="有效期" en="Validity period" /></template>
                                    <template #default="scope">
                                        <el-form-item :prop="`tagVOList.${key}.tagCertList[${scope.rowIndex}].yxq`"
                                            label-width="auto">
                                            <el-date-picker v-model="scope.row.yxq" type="date" v-if="editable"
                                                start-placeholder="有效期" value-format="YYYY-MM-DD" class="w100">
                                            </el-date-picker>
                                            <span v-else>{{ scope.row.yxq }}</span>
                                        </el-form-item>
                                    </template>
                                </vxe-column>
                                <vxe-column>
                                    <template #header><vp-label zh="附件" en="Attachment" /></template>
                                    <template #default="scope">
                                        <RowAttachment :attachmentList="scope.row.attachments" :readOnly="!editable"
                                            @attachmentListEmit="getAttachmentListEmit($event, scope.row)">
                                        </RowAttachment>
                                    </template>
                                </vxe-column>
                                <vxe-column align="center" width="100" v-if="editable">
                                    <template #header>
                                        <el-button circle @click="handleAddTag(key)">
                                            <SvgIcon name="ele-Plus"></SvgIcon>
                                        </el-button>
                                    </template>
                                    <template #default="scope">
                                        <el-button circle @click="handleDeleteTag(key, scope.rowIndex)">
                                            <SvgIcon name="ele-Minus"></SvgIcon>
                                        </el-button>
                                    </template>
                                </vxe-column>
                            </vp-vxe-table>
                        </el-form-item>
                    </vp-col>
                </el-row>
            </template>
        </vp-card>

        <vp-card>
            <template #header>
                <vp-label zh="其他信息" en="Other Information" />
            </template>
            <el-row>
                <vp-col :span="1">
                    <el-form-item>
                        <template #label><vp-label zh="联系人" en="Contact person" /></template>
                        <vp-vxe-table id="contactId" ref="tableRef" :data="formData.contactList" row-key="id"
                            minHeight="300">
                            <vxe-column field="xm">
                                <template #header><vp-label zh="姓名" en="Name" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`contactList[${scope.rowIndex}].xm`" label-width="auto">
                                        <el-input v-model="scope.row.xm" placeholder="请输入" v-if="editable" />
                                        <span v-else>{{ scope.row.xm }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="zw">
                                <template #header><vp-label zh="职位" en="Job" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`contactList[${scope.rowIndex}].zw`" label-width="auto">
                                        <el-input v-model="scope.row.zw" placeholder="请输入" v-if="editable" />
                                        <span v-else>{{ scope.row.zw }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="lxdh">
                                <template #header><vp-label zh="联系电话" en="Contact Phone" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`contactList[${scope.rowIndex}].lxdh`" label-width="auto">
                                        <el-input v-model="scope.row.lxdh" placeholder="请输入" v-if="editable" />
                                        <span v-else>{{ scope.row.lxdh }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="qtlxfs">
                                <template #header><vp-label zh="其他联系方式" en="Other Contact Phone" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`contactList[${scope.rowIndex}].qtlxfs`" label-width="auto">
                                        <el-input v-model="scope.row.qtlxfs" placeholder="请输入" v-if="editable" />
                                        <span v-else>{{ scope.row.qtlxfs }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="bz">
                                <template #header><vp-label zh="备注" en="Remark" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`contactList[${scope.rowIndex}].bz`" label-width="auto">
                                        <el-input v-model="scope.row.bz" placeholder="请输入" v-if="editable" />
                                        <span v-else>{{ scope.row.bz }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column align="center" width="100" v-if="editable">
                                <template #header>
                                    <el-button circle @click="handleAddContact()">
                                        <SvgIcon name="ele-Plus"></SvgIcon>
                                    </el-button>
                                </template>
                                <template #default="scope">
                                    <el-button circle @click="handleDeleteContact(scope.rowIndex)">
                                        <SvgIcon name="ele-Minus"></SvgIcon>
                                    </el-button>
                                </template>
                            </vxe-column>
                        </vp-vxe-table>
                    </el-form-item>
                </vp-col>
            </el-row>

            <el-row>
                <vp-col :span="1">
                    <el-form-item>
                        <template #label><vp-label zh="账户" en="Account" /></template>
                        <vp-vxe-table id="accountId" ref="tableRef" :data="formData.accountList" row-key="id"
                            minHeight="300">
                            <vxe-column field="mc">
                                <template #header><vp-label zh="名称" en="Name" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`accountList[${scope.rowIndex}].mc`" label-width="auto">
                                        <el-input v-model="scope.row.mc" placeholder="请输入" v-if="editable" />
                                        <span v-else>{{ scope.row.mc }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="khh">
                                <template #header><vp-label zh="开户行" en="Opening Bank" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`accountList[${scope.rowIndex}].khh`" label-width="auto">
                                        <el-input v-model="scope.row.khh" placeholder="请输入" v-if="editable" />
                                        <span v-else>{{ scope.row.khh }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="zh">
                                <template #header><vp-label zh="账号" en="Account" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`accountList[${scope.rowIndex}].zh`" label-width="auto">
                                        <el-input v-model="scope.row.zh" placeholder="请输入" v-if="editable" />
                                        <span v-else>{{ scope.row.zh }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="dz">
                                <template #header><vp-label zh="地址" en="Address" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`accountList[${scope.rowIndex}].dz`" label-width="auto">
                                        <el-input v-model="scope.row.dz" placeholder="请输入" v-if="editable" />
                                        <span v-else>{{ scope.row.dz }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="bz">
                                <template #header><vp-label zh="备注" en="Remarks" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`accountList[${scope.rowIndex}].bz`" label-width="auto">
                                        <el-input v-model="scope.row.bz" placeholder="请输入" v-if="editable" />
                                        <span v-else>{{ scope.row.bz }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column align="center" width="100" v-if="editable">
                                <template #header>
                                    <el-button circle @click="handleAddAccount()">
                                        <SvgIcon name="ele-Plus"></SvgIcon>
                                    </el-button>
                                </template>
                                <template #default="scope">
                                    <el-button circle @click="handleDeleteAccount(scope.rowIndex)">
                                        <SvgIcon name="ele-Minus"></SvgIcon>
                                    </el-button>
                                </template>
                            </vxe-column>
                        </vp-vxe-table>
                    </el-form-item>
                </vp-col>
            </el-row>

        </vp-card>

        <VpFileListCard :attachmentList="formData.attachments"
            @attachmentListEmit="getAttachmentListEmit($event, formData)" :readOnly="!(editable)">
            <template #header>
                <vp-label zh="附件" en="Attachment" />
            </template>
        </VpFileListCard>
    </el-form>
</template>
<script setup lang="ts" name="qualitySupplier">
import { computed, onMounted, ref } from 'vue'
import validateUtils from '/@/utils/validateUtils';

import RowAttachment from '/@/components/vp/file/VpRowAttachment.vue';

import VpDictCheckbox from '/@/components/vp/dict/VpDictCheckbox.vue';
import VpDictSelect from '/@/components/vp/dict/VpDictSelect.vue';
import VpFileListCard from '/@/components/vp/file/VpFileListCard.vue';

const props = defineProps({
    // 页面类型
    type: {
        type: String,
        default: 'add',
    },
    // 加载状态
    loading: {
        type: Boolean,
        default: false,
    },
    // 开启验证
    enableValid: {
        type: Boolean,
        default: true,
    }
});

const formData = ref({
    id: "",
    zt: 10,
    sjbb: "",
    gysbm: "",
    gysmc: "",
    gysywmc: "",
    jb: "",
    dz: "",
    bz: "",
    bqydm: "",
    zid: "",
    zxbs: null,
    fBbid: "",
    bBbid: "",

    fjglid: "",
    attachments: [] as any,

    tagList: [] as any,
    tagVOList: {} as any,

    contactList: [] as any,
    accountList: [] as any,
});

const formRules = {
    gysbm: [validateUtils.notNull],
    gysmc: [validateUtils.notNull],

}

const initFormData = () => {
    formData.value = {
        id: "",
        zt: 10,
        sjbb: "",
        gysbm: "",
        gysmc: "",
        gysywmc: "",
        jb: "",
        dz: "",
        bz: "",
        bqydm: "",
        zid: "",
        zxbs: null,
        fBbid: "",
        bBbid: "",


        fjglid: "",
        attachments: [] as any,

        tagList: [] as any,
        tagVOList: {} as any,

        contactList: [] as any,
        accountList: [] as any
    }
}

const editable = computed(() => {
    return props.type === 'add' || props.type === 'edit' || props.type === 'acceptanceProcess4Reedit';
})


const formRef = ref();

// 回显数据
const setData = (data: any) => {
    initFormData();
    formData.value = {
        ...formData.value,
        ...data,
    };
}

/**
 * 获取数据
 */
const getData = (zt: number): Promise<any> => {
    return new Promise((resolve, reject) => {

        let processedTagVOList = null;
        const originalTagVOList = formData.value.tagVOList;

        // 判断是否为空（空对象、undefined、null 都视为空）
        if (originalTagVOList && Object.keys(originalTagVOList).length > 0) {
            // 不为空时正常处理
            processedTagVOList = Object.fromEntries(
                Object.entries(originalTagVOList as any).map(([key, item]: [string, any]) => [
                    key,
                    {
                        bqmc: item.bqmc,
                        yxqKs: item.yxqKs,
                        yxqJs: item.yxqJs,
                        sqh: item.sqh,
                        sqfw: item.sqfw,
                        fjglid: item.fjglid,
                        attachments: item.attachments,
                        tagCertList: item.tagCertList.map((cert: any) => ({
                            lx: cert.lx,
                            bh: cert.bh,
                            sm: cert.sm,
                            bfrq: cert.bfrq,
                            yxq: cert.yxq,
                            bz: cert.bz,
                            attachments: cert.attachments
                        }))
                    }
                ])
            );
        }

        const submitData = {
            id: formData.value.id,
            zt: formData.value.zt,
            sjbb: formData.value.sjbb,
            gysbm: formData.value.gysbm,
            gysmc: formData.value.gysmc,
            gysywmc: formData.value.gysywmc,
            jb: formData.value.jb,
            dz: formData.value.dz,
            bz: formData.value.bz,
            bqydm: formData.value.bqydm,
            zid: formData.value.zid,
            zxbs: formData.value.zxbs,
            fBbid: formData.value.fBbid,
            bBbid: formData.value.bBbid,

            fjglid: formData.value.fjglid,
            attachments: formData.value.attachments,

            tagList: formData.value.tagList,
            tagVOList: processedTagVOList,

            contactList: formData.value.contactList,
            accountList: formData.value.accountList,
        };

        console.log('getData', formData.value);
        console.log('pureData', submitData);

        if (zt === 10 || !props.enableValid) {
            resolve(submitData);
        }
        formRef.value.validate((valid: boolean) => {
            if (valid) {
                resolve(submitData);
            } else {
                reject();
            }
        })
    })
}


//供应商联系人
const handleAddContact = () => {
    formData.value.contactList.push({
        id: "",
        mainid: "",
        xm: "",
        zw: "",
        lxdh: "",
        qtlxfs: "",
        bz: ""
    });
}
const handleDeleteContact = (index: number) => {
    formData.value.contactList.splice(index, 1);
}

//供应商账户
const handleAddAccount = () => {
    formData.value.accountList.push({
        id: "",
        mainid: "",
        mc: "",
        khh: "",
        zh: "",
        dz: "",
        bz: ""
    });
}
const handleDeleteAccount = (index: number) => {
    formData.value.accountList.splice(index, 1);
}

const handleComponentChange = (e: String[]) => {

    formData.value.tagList = e;

    console.log(e, "eee")

    const currentKeys = Object.keys(formData.value.tagVOList).map(String);
    const keysToRemove = currentKeys.filter(key => !e.includes(key));
    keysToRemove.forEach(key => {
        delete formData.value.tagVOList[key];
    });
    const keysToAdd = e.filter(key => !currentKeys.includes(key));
    keysToAdd.forEach(key => {
        formData.value.tagVOList[key] = {
            mainid: "",
            bqmc: String(key),
            yxqKs: "",
            yxqJs: "",
            sqh: "",
            sqfw: "",
            fjglid: "",
            attachments: [] as any,

            tagCertList: [] as any,
        };
    });
}

const handleAddTag = (key: number) => {
    formData.value.tagVOList[key].tagCertList.push({
        id: "",
        mainid: "",
        lx: "",
        bh: "",
        sm: "",
        bfrq: "",
        yxq: "",
        bz: "",
        fjglid: "",
        attachments: [] as any,
    });
}

const handleDeleteTag = (key: number, index: number) => {
    formData.value.tagVOList[key].tagCertList.splice(index, 1);
}

//文件赋值
const getAttachmentListEmit = (list: any, row: any) => {
    row.attachments = list;
}

defineExpose({
    setData,
    getData,
})
</script>